package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.dubbo.api.*;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.server.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class TestSoulService {

    @DubboReference(version = "1.0.0")
    private QuestionUserLockApi questionUserLockApi;

    @DubboReference(version = "1.0.0")
    private QuestionnaireApi questionnaireApi;

    @DubboReference(version = "1.0.0")
    private SoulQuestionApi soulQuestionApi;

    @DubboReference(version = "1.0.0")
    private SoulQuestionOptionApi soulQuestionOptionApi;

    @DubboReference(version = "1.0.0")
    private QuestionnaireResultApi questionnaireResultApi;

    @DubboReference(version = "1.0.0")
    private QuestionnaireReportApi questionnaireReportApi;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;


    /**
     * @return: java.util.List<com.tanhua.server.vo.QuestionnaireVo>
     * @author: LPW
     * @date: 2021/6/21 14:49
     * @description: 灵魂测试问卷列表
     */

    public List<QuestionnaireVo> soulQuestionnaire() {
        //获取用户id
        Long userId = UserThreadLocal.get();
        //返回对象
        List<QuestionnaireVo> questionnaireVoList = new ArrayList<>();
        //通过userId 查询QuestionUserLock表拿到问卷id和锁状态存到问卷vo里面

        List<QuestionUserLock> questionUserLockList = this.questionUserLockApi.selectList(userId);
        if (CollUtil.isEmpty(questionUserLockList)) {
            //给出默认值
            for (int i = 1; i <= 3; i++) {
                QuestionUserLock questionUserLock = new QuestionUserLock();
                if (i == 1) {
                    questionUserLock.setUserId(userId);
                    questionUserLock.setQuestionnaireId(i);
                    questionUserLock.setIsLock(0);
                } else {
                    questionUserLock.setUserId(userId);
                    questionUserLock.setQuestionnaireId(i);
                    questionUserLock.setIsLock(1);
                }
                this.questionUserLockApi.insert(questionUserLock);
                questionUserLockList.add(questionUserLock);
            }

        }
        for (QuestionUserLock questionUserLocks : questionUserLockList) {
            QuestionnaireVo questionnaireVo = new QuestionnaireVo();
            questionnaireVo.setId(Convert.toStr(questionUserLocks.getQuestionnaireId()));
            questionnaireVo.setIsLock(questionUserLocks.getIsLock());
            questionnaireVoList.add(questionnaireVo);
        }
        //拿出问卷Id的集合
        List<Object> questionnaireIdList = CollUtil.getFieldValues(questionUserLockList, "questionnaireId");
        //通过拿到的问卷id找到问题表中的数据存在返回问卷vo中
        List<Questionnaire> questionnaireList = this.questionnaireApi.queryByIdList(questionnaireIdList);
        for (Questionnaire questionnaire : questionnaireList) {
            for (QuestionnaireVo questionnaireVo : questionnaireVoList) {
                //把返回vo中的id与从问题表中拿到的id进行对比,确定存放的是同一个vo返回对象
                if (questionnaire.getId().toString().equals(questionnaireVo.getId().toString())) {
                    questionnaireVo.setLevel(questionnaire.getLevel());
                    questionnaireVo.setName(questionnaire.getName());
                    questionnaireVo.setCover(questionnaire.getCover());
                    questionnaireVo.setStar(questionnaire.getStar());
                    //根据用户id，查询当前用户最新的报告
                    QuestionnaireReport questionnaireReport = this.questionnaireReportApi.queryByUserId(userId, questionnaire.getId());
                    if (null != questionnaireReport) {
                        questionnaireVo.setReportId(Convert.toStr(questionnaireReport.getId()));
                    }
                }
            }
        }

        //把问题vo填充到问卷vo中
        for (QuestionnaireVo questionnaireVo : questionnaireVoList) {
            //获取问卷数据
            List<SoulQuestion> soulQuestionList = this.soulQuestionApi.queryListById(Convert.toLong(questionnaireVo.getId()));
            //封装soulQuestionVoList
            List<SoulQuestionVo> soulQuestionVoList = new ArrayList<>();
            //填充SoulQuestionVo的数据
            for (SoulQuestion soulQuestion : soulQuestionList) {
                SoulQuestionVo soulQuestionVo = new SoulQuestionVo();
                soulQuestionVo.setId(soulQuestion.getId().toString());
                soulQuestionVo.setQuestion(soulQuestion.getQuestion());
                //SoulQuestionVo中还有一个List<SoulQuestionOptionVo> options-----选项集合没有填充
                List<SoulQuestionOption> soulQuestionOptionList = this.soulQuestionOptionApi.queryListById(soulQuestion.getId());
                //封装soulQuestionOptionVoList
                List<SoulQuestionOptionVo> soulQuestionOptionVoList = new ArrayList<>();
                for (SoulQuestionOption soulQuestionOption : soulQuestionOptionList) {
                    SoulQuestionOptionVo soulQuestionOptionVo = new SoulQuestionOptionVo();
                    soulQuestionOptionVo.setId(soulQuestionOption.getId().toString());
                    soulQuestionOptionVo.setOption(soulQuestionOption.getContent());
                    soulQuestionOptionVoList.add(soulQuestionOptionVo);
                }
                //把选项vo集合填充到问题对象中
                soulQuestionVo.setOptions(soulQuestionOptionVoList);
                soulQuestionVoList.add(soulQuestionVo);
            }
            //把问题对象填充到返回问卷vo对象
            questionnaireVo.setQuestions(soulQuestionVoList);
        }


        return questionnaireVoList;
    }

    //提交问卷答案
    public Object soulTestAnswer(List<Answers> answersList) {

        int score = 0;
        Long questionId = 0L;
        //计算分数
        for (Answers answers : answersList) {
            questionId = answers.getQuestionId();
            Long optionId = answers.getOptionId();
            SoulQuestionOption soulQuestionOption = this.soulQuestionOptionApi.queryOneById(optionId);
            score += Integer.parseInt(soulQuestionOption.getScore());
        }

        //通过题目id查到对应的问卷id
        SoulQuestion soulQuestion = this.soulQuestionApi.queryOneById(questionId);
        Long questionnaireId = soulQuestion.getQuestionnaireId();


        //根据问卷id,查看结果表，看总分在哪个区间，判断你的性格，并把数据都添加到报告表里
        List<QuestionnaireResult> questionnaireResultList = this.questionnaireResultApi.queryListByQuestionnaireId(questionnaireId);

        QuestionnaireReport questionnaireReport = new QuestionnaireReport();
        questionnaireReport.setUserId(UserThreadLocal.get());
        questionnaireReport.setQuestionnaireId(questionnaireId);
        for (QuestionnaireResult questionnaireResult : questionnaireResultList) {
            String[] scoreArr = questionnaireResult.getScope().split(",");
            if (score >= Convert.toInt(scoreArr[0]) && score <= Convert.toInt(scoreArr[1])) {
                questionnaireReport.setResultId(questionnaireResult.getId());
                questionnaireReport.setResultType(StrUtil.sub(questionnaireResult.getContent(), 0, 3));
                break;
            }
        }
        String result = this.questionnaireReportApi.insert(questionnaireReport);
        if (StrUtil.isNotEmpty(result)) {

            return result;
        }
        //提交失败

        return ErrorResult.builder().errCode("500").errMessage("提交失败，请稍后重试").build();

    }

    /**
     * 测试结果
     *
     * @param reportId
     * @return
     */
    public TestResultVo testResult(Long reportId) {
        Long userId = UserThreadLocal.get();
        //返回数据封装对象、
        TestResultVo testResultVo = new TestResultVo();
        List<Dimensions> dimensionList = new ArrayList<>();
        //根据reportId获取report对象
        QuestionnaireReport questionnaireReport = this.questionnaireReportApi.queryById(reportId);
        //获取result对象
        QuestionnaireResult questionnaireResult = this.questionnaireResultApi.queryById(questionnaireReport.getResultId());
        //封装返回数据
        testResultVo.setConclusion(questionnaireResult.getContent());
        testResultVo.setCover(questionnaireResult.getCover());
        //性格数据
        Dimensions dimensions = new Dimensions();
        String[] characterOne = StrUtil.split(questionnaireResult.getCharacterOne(), "，");
        dimensions.setKey(characterOne[0]);
        dimensions.setValue(characterOne[1]);
        dimensionList.add(dimensions);

        String[] characterTwo = StrUtil.split(questionnaireResult.getCharacterTwo(), "，");
        dimensions.setKey(characterTwo[0]);
        dimensions.setValue(characterTwo[1]);
        dimensionList.add(dimensions);

        String[] characterThree = StrUtil.split(questionnaireResult.getCharacterThree(), "，");
        dimensions.setKey(characterThree[0]);
        dimensions.setValue(characterThree[1]);
        dimensionList.add(dimensions);

        String[] characterFour = StrUtil.split(questionnaireResult.getCharacterFour(), "，");
        dimensions.setKey(characterFour[0]);
        dimensions.setValue(characterFour[1]);
        dimensionList.add(dimensions);

        testResultVo.setDimensions(dimensionList);

        //封装similarYou
        //根据resultType,查询userIdlist
        List<QuestionnaireReport> questionnaireReportList = this.questionnaireReportApi.queryByResultType(questionnaireReport.getResultType());
        //if (CollUtil.isEmpty(questionnaireReportList)){
        //    //没有给出默认
        //
        //}
        List<Object> userIdList = CollUtil.getFieldValues(questionnaireReportList, "userId");
        //查询用户信息
        List<UserInfo> userInfoList = this.userInfoApi.queryByUserIdList(userIdList);

        List<SimilarYou> similarYouList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            //if (!ObjectUtil.equals(userInfo.getUserId(), UserThreadLocal.get())) {
            SimilarYou similarYou = new SimilarYou();
            similarYou.setId(Convert.toInt(userInfo.getUserId()));
            similarYou.setAvatar(userInfo.getLogo());
            similarYouList.add(similarYou);
            // }
        }
        testResultVo.setSimilarYou(similarYouList);

        //根据reportId和userId ，查询出用户最新报告是哪一套问卷，解锁下一套问卷
        QuestionnaireReport questionnaireReport1 = this.questionnaireReportApi.queryByUserIdAndId(userId, reportId);
        if (null != questionnaireReport1) {
            QuestionUserLock questionUserLock = new QuestionUserLock();
            questionUserLock.setIsLock(0);
            questionUserLock.setUserId(userId);
            questionUserLock.setQuestionnaireId(questionnaireReport1.getQuestionnaireId() + 1);
            this.questionUserLockApi.updateByUserId(userId, questionUserLock, questionnaireReport1.getQuestionnaireId());
        }

        return testResultVo;
    }
}
